<template>
  <el-dialog
    v-model="visible"
    title="露天矿边坡多元感知智能监管系统"
    width="95%"
    top="5vh"
    :close-on-click-modal="false"
    :destroy-on-close="true"
  >
    <div class="dashboard-layout">
      <el-card class="panel panel-left" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>设备运行状态</span>
          </div>
        </template>
        <div ref="deviceStatusPieRef" class="chart-container-pie"></div>
        <el-descriptions :column="1" border class="device-stats-desc">
          <el-descriptions-item label="雷达监测">
            <el-tag type="success">1 / 1</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="GNSS位移监测">
            <el-tag type="danger">48 / 50</el-tag>
            (2 故障)
          </el-descriptions-item>
          <el-descriptions-item label="深部位移监测">
            <el-tag type="success">10 / 10</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="环境监测">
            <el-tag type="success">5 / 5</el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <div class="panel panel-center">
        <div class="model-placeholder">
          <span>矿山三维模型 (3D Model Placeholder)</span>
        </div>
      </div>

      <el-tabs v-model="activeTab" type="border-card" class="panel panel-right" @tab-change="handleTabChange">
        
        <el-tab-pane label="实时预警" name="alarms">
          <div class="alarm-stats">
            <el-statistic title="红色预警" :value="alarmStats.red" class="alarm-stat-red" />
            <el-statistic title="橙色预警" :value="alarmStats.orange" class="alarm-stat-orange" />
            <el-statistic title="黄色预警" :value="alarmStats.yellow" class="alarm-stat-yellow" />
            <el-statistic title="蓝色预警" :value="alarmStats.blue" class="alarm-stat-blue" />
          </div>
          <el-divider />
          <el-timeline class="alarm-timeline">
            <el-timeline-item
              v-for="item in alarmList"
              :key="item.id"
              :timestamp="item.timestamp"
              :color="item.color"
            >
              {{ item.content }}
            </el-timeline-item>
          </el-timeline>
        </el-tab-pane>

        <el-tab-pane label="关键风险点" name="topn">
           <el-table :data="topNList" height="100%" stripe>
            <el-table-column type="index" label="排序" width="60" />
            <el-table-column prop="id" label="监测点" />
            <el-table-column prop="rate" label="速率 (mm/d)">
              <template #default="{ row }">
                <span :style="{ color: row.rate > 10 ? 'red' : (row.rate > 8 ? 'orange' : 'inherit') }">
                  {{ row.rate }} mm/d
                </span>
              </template>
            </el-table-column>
           </el-table>
        </el-tab-pane>

        <el-tab-pane label="预警处置" name="disposition">
          <div ref="dispositionRingRef" class="chart-container-ring"></div>
        </el-tab-pane>

        <el-tab-pane label="环境监测" name="env">
          <div class="env-monitoring">
            <el-progress type="dashboard" :percentage="envData.rainPercentage" :color="envData.rainColor">
              <template #default>
                <div class="progress-content">
                  <div>{{ envData.rain24h }} mm</div>
                  <div class="progress-label">24h降雨量</div>
                </div>
              </template>
            </el-progress>
            <el-statistic title="当前库水位" :value="envData.waterLevel" suffix="m" class="env-stat" />
          </div>
        </el-tab-pane>

        <el-tab-pane label="视频监控" name="video">
          <div class="video-placeholder">
            <span>(视频监控 D-001 画面)</span>
          </div>
        </el-tab-pane>
      </el-tabs>

      <div class="panel panel-bottom-charts">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>A区 - 累计位移</span>
            </div>
          </template>
          <div ref="trendLineChartARef" class="chart-container-multi-line"></div>
        </el-card>
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>B区 - 累计位移</span>
            </div>
          </template>
          <div ref="trendLineChartBRef" class="chart-container-multi-line"></div>
        </el-card>
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>C区 - 累计位移</span>
            </div>
          </template>
          <div ref="trendLineChartCRef" class="chart-container-multi-line"></div>
        </el-card>
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>D区 - 累计位移</span>
            </div>
          </template>
          <div ref="trendLineChartDRef" class="chart-container-multi-line"></div>
        </el-card>
      </div>

    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, nextTick, watch, onMounted, onBeforeUnmount } from "vue";
import { ElDialog, ElButton, ElCard, ElDescriptions, ElDescriptionsItem, ElTag, ElTabs, ElTabPane, ElStatistic, ElDivider, ElTimeline, ElTimelineItem, ElTable, ElTableColumn, ElProgress } from "element-plus";
import * as echarts from "echarts";
// 明确导入 ECharts 类型
import type { ECharts } from "echarts";

// === Dialog 控制 ===
const visible = ref<boolean>(false);

const open = () => {
  visible.value = true;
  // 必须在 Dialog 渲染 DOM 之后再初始化 ECharts
  nextTick(() => {
    initDevicePie();
    initMultiTrendLines(); // 初始化四个折线图
    // 默认显示第一个 Tab，如果第一个 Tab 也有 ECharts，也在这里 init
  });
};

const close = () => {
  visible.value = false;
};

// 暴露给父组件调用
defineExpose({ open, close });

// === ECharts 实例 ===
let devicePieInstance: ECharts | null = null;
let dispositionRingInstance: ECharts | null = null;

// 【修复】不再使用独立的 A, B, C, D 变量
// 【修复】声明一个数组来统一管理四个折线图实例
const chartInstances: (ECharts | null)[] = [null, null, null, null];


// ECharts DOM 引用
const deviceStatusPieRef = ref<HTMLElement | null>(null);
const dispositionRingRef = ref<HTMLElement | null>(null);
const trendLineChartARef = ref<HTMLElement | null>(null);
const trendLineChartBRef = ref<HTMLElement | null>(null);
const trendLineChartCRef = ref<HTMLElement | null>(null);
const trendLineChartDRef = ref<HTMLElement | null>(null);


// === 假数据 ===
const activeTab = ref('alarms');

// 报警统计
const alarmStats = ref({ red: 2, orange: 0, yellow: 5, blue: 10 });

// 报警时间线
const alarmList = ref([
  { id: 1, timestamp: '2025-11-06 14:05:10', content: 'P005 (A区) 速率 10.2 mm/d，触发红色预警', color: '#F56C6C' },
  { id: 2, timestamp: '2025-11-06 14:03:00', content: 'P012 (B区) 速率 8.1 mm/d，触发黄色预警', color: '#E6A23C' },
  { id: 3, timestamp: '2025-11-06 13:50:15', content: 'P033 (A区) 速率 7.5 mm/d，触发黄色预警', color: '#E6A23C' },
  { id: 4, timestamp: '2025-11-06 13:45:00', content: 'P102 (C区) 速率 3.1 mm/d，触发蓝色预警', color: '#409EFF' },
]);

// Top N 列表
const topNList = ref([
  { id: 'P005', rate: 10.2 },
  { id: 'P012', rate: 8.1 },
  { id: 'P033', rate: 7.5 },
  { id: 'P021', rate: 6.9 },
  { id: 'P102', rate: 3.1 },
]);

// 环境数据
const envData = ref({
  rain24h: 15.2, // 24小时降雨量
  rainThreshold: 50, // 假设暴雨阈值50mm
  get rainPercentage() { return (this.rain24h / this.rainThreshold) * 100 },
  get rainColor() { 
    if (this.rain24h > 40) return '#F56C6C'; // 大暴雨
    if (this.rain24h > 25) return '#E6A23C'; // 暴雨
    return '#67C23A'; // 正常
  },
  waterLevel: 105.5,
});


// === ECharts 初始化函数 ===

// 1. 左侧 - 设备状态饼图
const initDevicePie = () => {
  if (!deviceStatusPieRef.value) return;
  // 销毁旧实例
  if (devicePieInstance) {
    devicePieInstance.dispose();
  }
  devicePieInstance = echarts.init(deviceStatusPieRef.value);
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      bottom: '5%',
      left: 'center'
    },
    series: [
      {
        name: '设备状态',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 64, name: '在线' }, // 1+48+10+5
          { value: 2, name: '离线/故障' }
        ],
        color: ['#67C23A', '#F56C6C']
      }
    ]
  };
  devicePieInstance.setOption(option);
};

// 2. 右侧 Tab - 预警处置环形图
const initDispositionRing = () => {
  if (!dispositionRingRef.value) return;
  if (dispositionRingInstance) {
    dispositionRingInstance.dispose();
  }
  dispositionRingInstance = echarts.init(dispositionRingRef.value);
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: '5%',
      left: 'center'
    },
    series: [
      {
        name: '预警处置',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: true,
          formatter: '{b}: {c} ({d}%)'
        },
        data: [
          { value: 2, name: '未处理', itemStyle: { color: '#F56C6C' } },
          { value: 1, name: '处理中', itemStyle: { color: '#E6A23C' } },
          { value: 14, name: '已处理', itemStyle: { color: '#67C23A' } }
        ]
      }
    ]
  };
  dispositionRingInstance.setOption(option);
};


// 3. 底部 - 四个趋势折线图
// 封装一个通用的折线图配置函数
const getTrendLineOption = (title: string, data: number[]) => {
  return {
    title: {
      text: title,
      left: 'center',
      textStyle: {
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '10%',
      right: '10%',
      bottom: '15%',
      top: '25%', // 留出标题空间
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['13:00', '13:15', '13:30', '13:45', '14:00', '14:15', '14:30'],
      axisLabel: {
        rotate: 30 // X轴标签倾斜，避免重叠
      }
    },
    yAxis: {
      type: 'value',
      name: '位移 (mm)',
      nameTextStyle: {
        align: 'right'
      }
    },
    series: [
      {
        name: '累计位移',
        type: 'line',
        smooth: true,
        data: data,
        lineStyle: {
          color: '#409EFF'
        },
        itemStyle: {
          color: '#409EFF'
        },
        // 标线（阈值）- 可以根据实际数据动态生成
        markLine: {
          silent: true,
          symbol: 'none',
          data: [
            { yAxis: 50, name: '红色阈值', lineStyle: { color: '#F56C6C', type: 'dashed' }, label: { formatter: '{b}' } },
            { yAxis: 40, name: '橙色阈值', lineStyle: { color: '#E6A23C', type: 'dashed' }, label: { formatter: '{b}' } },
          ]
        },
        // 标点（最新报警）- 示例，实际应动态判断
        markPoint: {
          data: [
            {
              name: '最新报警',
              coord: ['14:15', 50.3], // 模拟一个报警点
              symbol: 'pin',
              symbolSize: 40,
              itemStyle: { color: '#F56C6C' }
            }
          ]
        }
      }
    ]
  };
};

const initMultiTrendLines = () => {
  const chartRefs = [trendLineChartARef, trendLineChartBRef, trendLineChartCRef, trendLineChartDRef];
  
  // 【修复】不再需要本地的 chartInstances 数组，直接使用全局的
  
  const titles = ['A区 - 累计位移', 'B区 - 累计位移', 'C区 - 累计位移', 'D区 - 累计位移'];
  // 模拟不同区域的假数据
  const datas = [
    [45.1, 46.2, 47.0, 48.3, 49.5, 50.3, 50.9], // A区数据，有报警点
    [30.5, 31.0, 31.8, 32.5, 33.1, 33.9, 34.5], // B区数据
    [20.1, 20.3, 20.8, 21.1, 21.5, 21.9, 22.3], // C区数据
    [10.0, 10.1, 10.3, 10.5, 10.7, 10.9, 11.1]  // D区数据
  ];

  chartRefs.forEach((ref, index) => {
    if (ref.value) {
      // 【修复】直接操作全局的 chartInstances 数组
      if (chartInstances[index]) {
        chartInstances[index]!.dispose();
      }
      chartInstances[index] = echarts.init(ref.value);
      chartInstances[index]!.setOption(getTrendLineOption(titles[index], datas[index]));
    }
  });
};


// === Tab 切换处理 ===
const handleTabChange = (tabName: string | number) => {
  if (tabName === 'disposition') {
    // 处置环形图
    nextTick(() => initDispositionRing());
  }
  // ... 可为其他 Tab 添加 ECharts 初始化
};

// === ECharts 窗口缩放自适应 ===
const resizeCharts = () => {
  devicePieInstance?.resize();
  dispositionRingInstance?.resize();
  
  // 【修复】循环全局的 chartInstances 数组
  chartInstances.forEach(chart => chart?.resize());
};

onMounted(() => {
  window.addEventListener('resize', resizeCharts);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeCharts);
  // 销毁 ECharts 实例
  devicePieInstance?.dispose();
  dispositionRingInstance?.dispose();

  // 【修复】循环全局的 chartInstances 数组
  chartInstances.forEach(chart => chart?.dispose());
});

</script>

<style lang="scss" scoped>
// CSS Grid 布局
.dashboard-layout {
  display: grid;
  // 定义网格区域
  grid-template-areas:
    "left center right"
    "bottom-charts bottom-charts bottom-charts"; // 底部现在通栏
  
  // 定义列宽: 左320px, 中间自适应, 右380px
  grid-template-columns: 320px 1fr 380px;
  
  // 定义行高: 上面自适应, 底部降低到 250px (原来是280px)
  grid-template-rows: 1fr 250px;
  
  height: 85vh; // 确保布局填满弹窗高度
  gap: 16px; // 网格间距
  padding: 10px;
  background-color: #f0f2f5; // 驾驶舱背景色
}

// 面板通用样式
.panel {
  box-sizing: border-box;
  // 让 el-card 填满网格单元
  :deep(.el-card__body) {
    height: calc(100% - 60px); // 减去 header 高度
    padding: 10px;
  }
}

// 分配网格区域
.panel-left {
  grid-area: left;
  display: flex;
  flex-direction: column;
}
.panel-center {
  grid-area: center;
  background: #0a213c; // 深色背景模拟
  border-radius: 4px;
}
.panel-right {
  grid-area: right;
  display: flex; // 让 tabs 内部也 flex 布局
  flex-direction: column;
}
// 新增底部图表区域的样式
.panel-bottom-charts {
  grid-area: bottom-charts;
  display: grid; // 内部再使用 grid 布局
  grid-template-columns: repeat(4, 1fr); // 四个图表平分宽度
  gap: 16px; // 图表间的间距
}
.chart-card {
  height: 100%; // 确保每个图表卡片填满父容器的高度
}


// --- 特定面板样式 ---

// 1. 左侧 - 设备状态
.chart-container-pie {
  width: 100%;
  height: 180px; // 略微调小
}
.device-stats-desc {
  margin-top: 15px;
  flex: 1; // 让描述信息区占满剩余高度
  overflow-y: auto; // 溢出滚动
}

// 2. 中心 - 3D 占位
.model-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #fff;
  font-size: 20px;
  background-color: #333;
  border: 1px dashed #555;
  border-radius: 4px;
}

// 3. 右侧 - Tabs
:deep(.el-tabs__content) {
  flex: 1; // 让 tab 内容区占满剩余高度
  overflow-y: auto; // 内容溢出时滚动
}
.el-tab-pane {
  height: 100%;
  display: flex; // 内部内容弹性布局
  flex-direction: column;
}

// 实时预警
.alarm-stats {
  display: flex;
  justify-content: space-around;
  text-align: center;
  margin-bottom: 10px;
  :deep(.el-statistic__head) {
    font-size: 14px;
  }
  .alarm-stat-red :deep(.el-statistic__content) { color: #F56C6C; }
  .alarm-stat-orange :deep(.el-statistic__content) { color: #E6A23C; }
  .alarm-stat-yellow :deep(.el-statistic__content) { color: #E6A23C; } // 沿用橙色
  .alarm-stat-blue :deep(.el-statistic__content) { color: #409EFF; }
}
.alarm-timeline {
  margin-top: 5px;
  max-height: 400px; // 限制高度
  overflow-y: auto;
  flex: 1; // 让时间线占满剩余高度
}

// Top N 表格
.el-table {
  flex: 1;
}

// 预警处置
.chart-container-ring {
  width: 100%;
  height: 300px; // 给环形图一个固定高度
}

// 环境监测
.env-monitoring {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 20px;
  padding-top: 20px;
  flex: 1;
  .env-stat {
    text-align: center;
  }
  .progress-content {
    font-size: 14px;
  }
  .progress-label {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    margin-top: 5px;
  }
}

// 视频占位
.video-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  min-height: 300px;
  background-color: #000;
  color: #fff;
  border-radius: 4px;
}

// 4. 底部 - 四个折线图
.chart-container-multi-line {
  width: 100%;
  height: 100%;
  min-height: 180px; // 确保每个小图表的最小高度
}

// 弹窗样式微调
:deep(.el-dialog__body) {
  padding: 0; // 移除 el-dialog 的默认 padding，让我们的 grid 占满
}
:deep(.el-dialog__header) {
  padding-bottom: 10px; // 标题和内容间距
}
</style>